<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerAddOrUpdateSwipperModal"
    :title="displayModuleTitle"
    @ok="onCategorySwipperOkButtonClick"
    width="600px"
    :body-style="{ height: '500px' }"
  >
    <BasicForm @register="registerAddOrUpdateSwipperForm">
      <template #selectArticleButton="{ model, field }">
        <a-button type="primary" @click="onSelectArticleButtonClick"
          >从已发布文章中选择(使用文章的标题及封面图片)</a-button
        >
      </template>
    </BasicForm>
    <SelectArticle @register="registerSelectArticleModal" @success="onSelectArticleOkButtonClick" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, computed } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';

  import { swipperFormSchema } from './swipper.data';
  import { addSwipper, updateSwipper } from '/@/api/cms/swipper';
  import SelectArticle from './SelectArticle.vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();

  const [registerSelectArticleModal, { openModal: openSelectArticleModal }] = useModal();

  export default defineComponent({
    name: 'AddOrUpdateSwipper',
    components: { BasicModal, BasicForm, SelectArticle },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();

      //栏目id
      const categoryId = ref('');
      //栏目名称
      const categoryName = ref('');
      const swipper = ref({});

      /**
       * 显示的模块标题，用于显示在弹出框中的标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      const [
        registerAddOrUpdateSwipperForm,
        { setFieldsValue, resetFields, validate, updateSchema, getFieldsValue },
      ] = useForm({
        labelWidth: 140,
        schemas: swipperFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerAddOrUpdateSwipperModal, { setModalProps, closeModal }] = useModalInner(
        async (data: QcUnifyTransToChildProps) => {
          //接收父组件传递的数据
          console.log('registerAddOrUpdateSwipperModal data', data);
          if (data != undefined && data != null) {
            qcUnifyProps.value = unref(data);
            //从父组件中传递过来的栏目ID
            categoryId.value = data.dataId;
            categoryName.value = data.dataTitle;
          }

          //如果是修改，为父组件中传递过来的修改的数据
          if (data?.model) {
            swipper.value = data.model;
          }

          resetFields(); //重置表单
          setModalProps({ confirmLoading: false });

          //给表单中的轮播图分组选择组件和素材来源组件添加事件
          updateSchema({
            field: 'groupid',
            componentProps: {
              onChange: handleFormGroupIdChange,
            },
          });

          //给表单中的图片上传组件添加事件
          updateSchema({
            field: 'files',
            componentProps: {
              onChange: handleImageUploadChange,
            },
          });

          //如果是新增数据
          if (qcUnifyProps.value?.operateType == OperationTypeEnum.ADD) {
            // 将传入的栏目id设置到表单中
            setFieldsValue({
              cid: categoryId.value,
            });
          }

          // 如果是修改数据
          if (qcUnifyProps.value?.operateType == OperationTypeEnum.EDIT) {
            //根据传入的数据进行赋值回显
            setFieldsValue({
              ...swipper.value,
            });
          }
        },
      );

      /**
       * 轮播图分组选择事件
       */
      async function handleFormGroupIdChange(value) {
        console.log('handleFormGroupIdChange', value);
      }

      /**
       * 图片上传组件事件
       */
      async function handleImageUploadChange(fileList) {
        console.log('handleImageUploadChange', fileList);
        if (fileList != undefined && fileList != null && fileList.length > 0x0) {
          let imageId = fileList[0].id;
          //给表单中的图片ID进行赋值
          setFieldsValue({
            fid: imageId,
          });
        }
      }

      /**
       * 打开选择文章窗口
       */
      function onSelectArticleButtonClick() {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: qcUnifyProps.value.moduleName,
          operateType: OperationTypeEnum.CUSTOME,
          operateString: '从已发布文章中选择轮播图素材',
          dataId: qcUnifyProps.value?.dataId,
          dataTitle: qcUnifyProps.value?.dataTitle,
        };

        //使用props传递数据至子组件，在data参数中指定
        openSelectArticleModal(true, propsData);
      }

      /**
       * 选择文章窗口点击选中完成事件
       */
      function onSelectArticleOkButtonClick(record: Recordable) {
        console.log('onSelectArticleOkButtonClick', record);
        //获取选择的文章信息进行赋值
        setFieldsValue({
          title: record.title,
          articleid: record.id,
          fid: record.cover,
        });
      }

      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onCategorySwipperOkButtonClick() {
        const values = await validate();
        console.log('values', values);
        setModalProps({ confirmLoading: true });

        //如果有从文章中选择图片使用文章中的图片ID，如果没有获取上传文件组件中的图片ID
        if (
          values.fid == undefined ||
          values.fid == null ||
          values.fid === 0 ||
          values.fid === '0'
        ) {
          if (values.selectFile && values.files && values.files.length > 0x0) {
            //将json对象转换为字符串
            values.fid = JSON.stringify(values.files[0].id);
          }
        }

        //根据指定的操作类型分别进行提交数据和处理
        if (qcUnifyProps.value?.operateType == OperationTypeEnum.ADD) {
          try {
            //调用接口进行保存
            addSwipper(values)
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (qcUnifyProps.value?.operateType == OperationTypeEnum.EDIT) {
          //调用接口进行保存
          updateSwipper(values)
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('保存成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }

      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }

      return {
        displayModuleTitle,
        registerAddOrUpdateSwipperModal,
        registerAddOrUpdateSwipperForm,
        registerSelectArticleModal,
        handleFormGroupIdChange,
        handleImageUploadChange,
        onSelectArticleButtonClick,
        onCategorySwipperOkButtonClick,
        onSelectArticleOkButtonClick,
        opSuccess,
      };
    },
  });
</script>
